package com.lwq.controller;

import com.lwq.util.*;
import com.lwq.annotation.PermissionController;
import com.lwq.annotation.PermissionInterface;
import com.lwq.config.CoreConfig;
import com.lwq.config.ServerConfig;
import com.lwq.constants.Constants;
import com.lwq.model.Result;
import com.lwq.service.system.DictService;
import com.lwq.util.file.FileUploadUtils;
import com.lwq.util.file.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Description:
 * Author: LiuWenQing
 * Datetime: 2021/6/15
 */
@RestController
@PermissionController(type = "system")
public class CommonController extends BaseController {


    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private DictService dictService;
     @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete 是否删除
     */
    @GetMapping("common/download")
    @PermissionInterface(code = "system.download", name="下载")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            if (!FileUtils.checkAllowDownload(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = CoreConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete)
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用上传请求
     */
    @PostMapping("/common/upload")
    @PermissionInterface(code = "system.upload", name="上传")
    public Result uploadFile(MultipartFile file) throws Exception
    {
        try {
            // 上传文件路径
            String filePath = CoreConfig.getPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            Map<String,Object> map = new HashMap<>();
            map.put("fileName", fileName);
            map.put("url", url);
            return Result.ok(map);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 本地资源通用下载
     */
    @GetMapping("/common/download/resource")
    @PermissionInterface(code = "system.download", name="下载")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        try
        {
            if (!FileUtils.checkAllowDownload(resource))
            {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = CoreConfig.getPath();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 根据code查询字典值
     */
    @GetMapping(value = "common/dictCode")
    @PermissionInterface(name="查询字典", code="dict.query")
    public Object findByDictCode(@RequestParam String code,@RequestParam(required = false) String exclude){
        return dictService.findDictByCode(code,exclude);
    }

    @GetMapping("testLock")
    public void testLock(){
        try {
            if (RedisLock.lockByNX(message.getId() + ":N", redisTemplate)) {
                addSet(RedisUtil.READED_N + message.getId(), userId);
            } else {
                WebChatMessage finalTopMessage = message;
                String rs = TaskUtil.foreachTask(() -> {
                    if (RedisLock.lockByNX(finalTopMessage.getId() + ":N", redisTemplate)) {
                        addSet(RedisUtil.READED_N + finalTopMessage.getId(), userId);
                        return "success";
                    } else {
                        return null;
                    }
                }, retryTimes, retryTimeout);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            RedisLock.unlockByNX(message.getId() + ":N", redisTemplate);
        }
    }

//    /**
//     * 导入excel接口
//     * @param file
//     * @return
//     */
//    @PostMapping(value="/common/handleTable")
//    public Object handleTable(MultipartFile file) throws Exception{
//        ExcelUtil<TestModel> util = new ExcelUtil<>(TestModel.class);
//        List<TestModel> list =util.importExcel(file.getInputStream());
//        list.forEach(e->{
//            testMapper.insert(e);
//        });
//        return list;
//    }
}
